const YouTubeDownloader = require('./downloader');
const readline = require('readline');

const rl = readline.createInterface({
  input: process.stdin,
  output: process.stdout
});

const downloader = new YouTubeDownloader('./downloads');

function question(prompt) {
  return new Promise((resolve) => {
    rl.question(prompt, resolve);
  });
}

async function main() {
  console.log('🎥 YouTube 视频下载器');
  console.log('====================');

  // 检查 yt-dlp
  const ytdlpAvailable = await downloader.checkYtDlp();
  if (!ytdlpAvailable) {
    console.error('❌ yt-dlp 未安装或不可用');
    console.log('请先安装 yt-dlp: https://github.com/yt-dlp/yt-dlp');
    process.exit(1);
  }
  console.log('✅ yt-dlp 可用');

  while (true) {
    console.log('\n选择操作:');
    console.log('1. 下载单个视频');
    console.log('2. 下载播放列表');
    console.log('3. 获取视频信息');
    console.log('4. 查看下载的文件');
    console.log('5. 退出');

    const choice = await question('请输入选择 (1-5): ');

    switch (choice) {
      case '1':
        await downloadSingleVideo();
        break;
      case '2':
        await downloadPlaylist();
        break;
      case '3':
        await getVideoInfo();
        break;
      case '4':
        await listDownloadedFiles();
        break;
      case '5':
        console.log('再见!');
        rl.close();
        return;
      default:
        console.log('无效选择，请重试');
    }
  }
}

async function downloadSingleVideo() {
  const url = await question('请输入视频 URL: ');
  
  console.log('\n选择质量:');
  console.log('1. 最佳质量 (best)');
  console.log('2. 最差质量 (worst)');
  console.log('3. 仅音频 (mp3)');
  console.log('4. 自定义');

  const qualityChoice = await question('请选择 (1-4): ');
  let options = {};

  switch (qualityChoice) {
    case '1':
      options.quality = 'best';
      break;
    case '2':
      options.quality = 'worst';
      break;
    case '3':
      options.audioOnly = true;
      options.audioFormat = 'mp3';
      break;
    case '4':
      options.quality = await question('请输入格式代码 (如 720p, 480p): ');
      break;
    default:
      options.quality = 'best';
  }

  const subtitles = await question('是否下载字幕? (y/n): ');
  if (subtitles.toLowerCase() === 'y') {
    options.subtitles = true;
    options.subtitleLang = await question('字幕语言 (默认 en): ') || 'en';
  }

  try {
    console.log('\n开始下载...');
    const result = await downloader.downloadVideo(url, options);
    console.log('✅ 下载完成!');
  } catch (error) {
    console.error('❌ 下载失败:', error.message);
  }
}

async function downloadPlaylist() {
  const url = await question('请输入播放列表 URL: ');
  
  try {
    console.log('\n获取播放列表信息...');
    const videos = await downloader.getPlaylistInfo(url);
    console.log(`📋 播放列表包含 ${videos.length} 个视频`);
    
    const confirm = await question('是否继续下载? (y/n): ');
    if (confirm.toLowerCase() !== 'y') {
      return;
    }

    console.log('\n选择质量:');
    console.log('1. 最佳质量');
    console.log('2. 仅音频 (mp3)');
    
    const qualityChoice = await question('请选择 (1-2): ');
    let options = { playlist: true };

    if (qualityChoice === '2') {
      options.audioOnly = true;
      options.audioFormat = 'mp3';
    } else {
      options.quality = 'best';
    }

    console.log('\n开始下载播放列表...');
    const result = await downloader.downloadVideo(url, options);
    console.log('✅ 播放列表下载完成!');
  } catch (error) {
    console.error('❌ 下载失败:', error.message);
  }
}

async function getVideoInfo() {
  const url = await question('请输入视频 URL: ');
  
  try {
    console.log('\n获取视频信息...');
    const info = await downloader.getVideoInfo(url);
    
    console.log('\n📹 视频信息:');
    console.log(`标题: ${info.title}`);
    console.log(`上传者: ${info.uploader}`);
    console.log(`时长: ${Math.floor(info.duration / 60)}:${(info.duration % 60).toString().padStart(2, '0')}`);
    console.log(`观看次数: ${info.view_count?.toLocaleString() || 'N/A'}`);
    console.log(`描述: ${info.description?.substring(0, 200)}...`);
  } catch (error) {
    console.error('❌ 获取信息失败:', error.message);
  }
}

async function listDownloadedFiles() {
  try {
    const files = await downloader.getDownloadedFiles();
    
    if (files.length === 0) {
      console.log('\n📁 没有下载的文件');
      return;
    }

    console.log('\n📁 下载的文件:');
    files.forEach((file, index) => {
      const sizeInMB = (file.size / 1024 / 1024).toFixed(2);
      console.log(`${index + 1}. ${file.name} (${sizeInMB} MB)`);
    });
  } catch (error) {
    console.error('❌ 获取文件列表失败:', error.message);
  }
}

// 处理程序退出
process.on('SIGINT', () => {
  console.log('\n\n👋 程序已退出');
  rl.close();
  process.exit(0);
});

if (require.main === module) {
  main().catch(console.error);
}

module.exports = { main };